package com.tomkk;

import com.google.gson.Gson;
import com.tomkk.utils.Error;
import com.tomkk.utils.MysqlOperation;
import com.tomkk.utils.Success;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.SQLException;

/**
 * Created by Tomkk on 2016/5/23.
 */
@WebServlet(name = "ChangeUserRoleServlet",urlPatterns = "/changeUserRole")
public class ChangeUserRoleServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("utf-8");
        response.setCharacterEncoding("utf-8");
        int user_id = Integer.parseInt(request.getParameter("user_id"));
        int role = Integer.parseInt(request.getParameter("role"));
        String sql = "UPDATE user set role = " + role + " WHERE user_id = " + user_id + ";";
        Gson gson = new Gson();
        MysqlOperation operation = new MysqlOperation();
        operation.checkConn();
        int rows = operation.update(sql);
        String json = null;
        if(rows == 1){
            json = gson.toJson(new Success(0,"修改成功"));
        }else{
            json = gson.toJson(new Error(2,"服务器错误"));
        }
        PrintWriter writer = response.getWriter();
        writer.print(json);
        writer.flush();
        try {
            operation.closeDB();
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

    }
}
